/**
 * Copyright (c) 2007 lyxite.com
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a 
 * copy of this software and associated documentation files (the "Software"), 
 * to deal in the Software without restriction, including without limitation 
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the 
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in 
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 * DEALINGS IN THE SOFTWARE.
 */
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;

namespace Weys.Lib
{
	/// <summary>
	/// main capture dialog.
	/// </summary>
	public class WeysForm : System.Windows.Forms.Form
	{
		private System.ComponentModel.IContainer components;

		private Skin skin;
		
		private Settings settings;

		private System.Windows.Forms.ContextMenu contextMenu;
		private System.Windows.Forms.MenuItem menuItem7;
		private System.Windows.Forms.MenuItem menuItemSkins;
		private System.Windows.Forms.MenuItem menuItemDefault;
		private System.Windows.Forms.MenuItem menuItemCapture;
		private System.Windows.Forms.MenuItem menuItemCaptureSave;
		private System.Windows.Forms.MenuItem menuItemSettings;
		private System.Windows.Forms.MenuItem menuItemHelp;
		private System.Windows.Forms.MenuItem menuItemAbout;
		private System.Windows.Forms.MenuItem menuItemSwitch;
		private System.Windows.Forms.MenuItem menuItemExit;
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.MenuItem menuItem2;
		private System.Windows.Forms.MenuItem menuItem3;
		private System.Windows.Forms.TextBox textBoxWidth;
		private System.Windows.Forms.TextBox textBoxHeight;
		
		private System.Windows.Forms.Button buttonUpdate;
		private System.Windows.Forms.PictureBox pictureBox1;
		private Rectangle captureArea = new Rectangle(20,30,176,220);
		private System.Windows.Forms.ToolTip toolTip;
		private Rectangle BANNER = new Rectangle(20,20,40,70);

        private Form aboutDialog = null;

        public Form AboutDialog
        {
            set { aboutDialog = value; }
        }

		public WeysForm()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

            string skindir = Application.StartupPath + @"\skins";

            if (!Directory.Exists(skindir))
                Directory.CreateDirectory(skindir);
            
			string [] files = Directory.GetFiles(skindir, "*.xml");
			foreach(string f in files)
			{
				MenuItem mi = new MenuItem(Path.GetFileNameWithoutExtension(f).Replace("_", " "));
                mi.Tag = f;
				mi.Click += new System.EventHandler(this.SkinMenuItem_Click);
				menuItemSkins.MenuItems.Add(mi);
			}
			LoadSettings();
		}

		private void LoadSettings()
		{
			//loading settings
			if(File.Exists("settings.xml"))
			{
				try
				{
					settings = Settings.Load("settings.xml");
					this.Location = settings.Position;
					if(settings.SkinFileName == "")
					{
						captureArea.Size = settings.DefaultCaptureSize;
						ApplySkin(null);
					}
					else
					{
						Skin s = Skin.Load(@".\skins\"+settings.SkinFileName);
						s.Mode = settings.SkinMode;
						ApplySkin(s);
						foreach(MenuItem mi in menuItemSkins.MenuItems)
						{
							if(settings.SkinFileName.Equals(mi.Tag))
								mi.Checked = true;
							else
								mi.Checked = false;
						}
					}
				}
				catch(Exception ex)
				{
					string s = ex.Message;
					MessageBox.Show(this, "Error loading setting file settings.xml. Default settings are apllied", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
					settings = new Settings();
					settings.DefaultCaptureSize = captureArea.Size;
					CenterWindow();
					ApplySkin(null);
				}
			}
			else
			{
				settings = new Settings();				
				settings.DefaultCaptureSize = captureArea.Size;
				//Width = captureArea.Width + BANNER.Width;
				//Height = captureArea.Height + BANNER.Height;
				CenterWindow();
				ApplySkin(null);
			}
			settings.SettingFilePath = Directory.GetCurrentDirectory();
		}
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(WeysForm));
			this.contextMenu = new System.Windows.Forms.ContextMenu();
			this.menuItemCapture = new System.Windows.Forms.MenuItem();
			this.menuItemCaptureSave = new System.Windows.Forms.MenuItem();
			this.menuItem1 = new System.Windows.Forms.MenuItem();
			this.menuItemSwitch = new System.Windows.Forms.MenuItem();
			this.menuItemSkins = new System.Windows.Forms.MenuItem();
			this.menuItemDefault = new System.Windows.Forms.MenuItem();
			this.menuItem7 = new System.Windows.Forms.MenuItem();
			this.menuItemSettings = new System.Windows.Forms.MenuItem();
			this.menuItem2 = new System.Windows.Forms.MenuItem();
			this.menuItemExit = new System.Windows.Forms.MenuItem();
			this.menuItem3 = new System.Windows.Forms.MenuItem();
			this.menuItemHelp = new System.Windows.Forms.MenuItem();
			this.menuItemAbout = new System.Windows.Forms.MenuItem();
			this.textBoxWidth = new System.Windows.Forms.TextBox();
			this.textBoxHeight = new System.Windows.Forms.TextBox();
			this.buttonUpdate = new System.Windows.Forms.Button();
			this.pictureBox1 = new System.Windows.Forms.PictureBox();
			this.toolTip = new System.Windows.Forms.ToolTip(this.components);
			this.SuspendLayout();
			// 
			// contextMenu
			// 
			this.contextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																						this.menuItemCapture,
																						this.menuItemCaptureSave,
																						this.menuItem1,
																						this.menuItemSwitch,
																						this.menuItemSkins,
																						this.menuItemSettings,
																						this.menuItem2,
																						this.menuItemExit,
																						this.menuItem3,
																						this.menuItemHelp,
																						this.menuItemAbout});
			this.contextMenu.Popup += new System.EventHandler(this.contextMenu_Popup);
			// 
			// menuItemCapture
			// 
			this.menuItemCapture.Index = 0;
			this.menuItemCapture.Text = "&Capture";
			this.menuItemCapture.Click += new System.EventHandler(this.menuItemCapture_Click);
			// 
			// menuItemCaptureSave
			// 
			this.menuItemCaptureSave.Index = 1;
			this.menuItemCaptureSave.Text = "Ca&pture && Save";
			this.menuItemCaptureSave.Click += new System.EventHandler(this.menuItemCaptureSave_Click);
			// 
			// menuItem1
			// 
			this.menuItem1.Index = 2;
			this.menuItem1.Text = "-";
			// 
			// menuItemSwitch
			// 
			this.menuItemSwitch.Index = 3;
			this.menuItemSwitch.Text = "S&witch";
			this.menuItemSwitch.Click += new System.EventHandler(this.menuItemSwitch_Click);
			// 
			// menuItemSkins
			// 
			this.menuItemSkins.Index = 4;
			this.menuItemSkins.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																						  this.menuItemDefault,
																						  this.menuItem7});
			this.menuItemSkins.Text = "S&kins";
			// 
			// menuItemDefault
			// 
			this.menuItemDefault.Checked = true;
			this.menuItemDefault.Index = 0;
			this.menuItemDefault.Text = "Plain (Sizable)";
			this.menuItemDefault.Click += new System.EventHandler(this.menuItemDefault_Click);
			// 
			// menuItem7
			// 
			this.menuItem7.Index = 1;
			this.menuItem7.Text = "-";
			// 
			// menuItemSettings
			// 
			this.menuItemSettings.Index = 5;
			this.menuItemSettings.Text = "&Settings";
			this.menuItemSettings.Click += new System.EventHandler(this.menuItemSettings_Click);
			// 
			// menuItem2
			// 
			this.menuItem2.Index = 6;
			this.menuItem2.Text = "-";
			// 
			// menuItemExit
			// 
			this.menuItemExit.Index = 7;
			this.menuItemExit.Text = "E&xit";
			this.menuItemExit.Click += new System.EventHandler(this.menuItemExit_Click);
			// 
			// menuItem3
			// 
			this.menuItem3.Index = 8;
			this.menuItem3.Text = "-";
			// 
			// menuItemHelp
			// 
			this.menuItemHelp.Index = 9;
			this.menuItemHelp.Text = "&Help";
			this.menuItemHelp.Click += new System.EventHandler(this.menuItemHelp_Click);
			// 
			// menuItemAbout
			// 
			this.menuItemAbout.Index = 10;
			this.menuItemAbout.Text = "&About";
			this.menuItemAbout.Click += new System.EventHandler(this.menuItemAbout_Click);
			// 
			// textBoxWidth
			// 
			this.textBoxWidth.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
			this.textBoxWidth.Location = new System.Drawing.Point(8, 280);
			this.textBoxWidth.Name = "textBoxWidth";
			this.textBoxWidth.Size = new System.Drawing.Size(40, 20);
			this.textBoxWidth.TabIndex = 0;
			this.textBoxWidth.Text = "176";
			this.textBoxWidth.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
			this.toolTip.SetToolTip(this.textBoxWidth, "Width of capture area.\r\nPress enter to apply changes");
			this.textBoxWidth.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBoxWidth_KeyDown);
			// 
			// textBoxHeight
			// 
			this.textBoxHeight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
			this.textBoxHeight.Location = new System.Drawing.Point(168, 280);
			this.textBoxHeight.Name = "textBoxHeight";
			this.textBoxHeight.Size = new System.Drawing.Size(40, 20);
			this.textBoxHeight.TabIndex = 1;
			this.textBoxHeight.Text = "220";
			this.textBoxHeight.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
			this.toolTip.SetToolTip(this.textBoxHeight, "Height of capture area.\r\nPress enter to apply changes");
			this.textBoxHeight.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBoxHeight_KeyDown);
			// 
			// buttonUpdate
			// 
			this.buttonUpdate.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
			this.buttonUpdate.Location = new System.Drawing.Point(80, 248);
			this.buttonUpdate.Name = "buttonUpdate";
			this.buttonUpdate.Size = new System.Drawing.Size(56, 23);
			this.buttonUpdate.TabIndex = 4;
			this.buttonUpdate.Text = "Update";
			this.buttonUpdate.Visible = false;
			this.buttonUpdate.Click += new System.EventHandler(this.buttonUpdate_Click);
			// 
			// pictureBox1
			// 
			this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
			this.pictureBox1.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
			this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
			this.pictureBox1.Location = new System.Drawing.Point(203, 299);
			this.pictureBox1.Name = "pictureBox1";
			this.pictureBox1.Size = new System.Drawing.Size(13, 13);
			this.pictureBox1.TabIndex = 5;
			this.pictureBox1.TabStop = false;
			this.pictureBox1.MouseEnter += new System.EventHandler(this.pictureBox1_MouseEnter);
			this.pictureBox1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseMove);
			this.pictureBox1.MouseLeave += new System.EventHandler(this.pictureBox1_MouseLeave);
			this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown);
			// 
			// toolTip
			// 
			this.toolTip.AutomaticDelay = 100;
			this.toolTip.AutoPopDelay = 4000;
			this.toolTip.InitialDelay = 100;
			this.toolTip.ReshowDelay = 20;
			// 
			// WeysForm
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(216, 312);
			this.Controls.Add(this.pictureBox1);
			this.Controls.Add(this.buttonUpdate);
			this.Controls.Add(this.textBoxWidth);
			this.Controls.Add(this.textBoxHeight);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
			this.MinimumSize = new System.Drawing.Size(104, 150);
			this.Name = "WeysForm";
			this.ShowInTaskbar = false;
			this.Text = "Weys";
			this.TopMost = true;
			this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.WeysForm_KeyDown);
			this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.WeysForm_MouseDown);
			this.Closing += new System.ComponentModel.CancelEventHandler(this.WeysForm_Closing);
			this.SizeChanged += new System.EventHandler(this.WeysForm_SizeChanged);
			this.Load += new System.EventHandler(this.WeysForm_Load);
			this.DoubleClick += new System.EventHandler(this.WeysForm_DoubleClick);
			this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.WeysForm_MouseUp);
			this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.WeysForm_MouseMove);
			this.ResumeLayout(false);

		}
		#endregion

		private Image CaptureFullScreen()
		{
			Image MyImage;
			this.Visible = false;
			IntPtr dc1 = WinAPI.CreateDC("DISPLAY", null, null, (IntPtr)null);
			Graphics g1 = Graphics.FromHdc(dc1);
			MyImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, g1);
			Graphics g2 = Graphics.FromImage(MyImage);
			Visible = false;
			dc1 = g1.GetHdc();
			IntPtr dc2 = g2.GetHdc();
			WinAPI.BitBlt(dc2, 0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, dc1, 0, 0, 13369376);
			g1.ReleaseHdc(dc1);
			g2.ReleaseHdc(dc2);
			Visible = true;
			g2.Dispose();
			return MyImage;
		}

		private Image CapturePartial()
		{
			Image MyImage;
			this.Visible = false;
			IntPtr dc1 = WinAPI.CreateDC("DISPLAY", null, null, (IntPtr)null);
			Graphics g1 = Graphics.FromHdc(dc1);
			MyImage = new Bitmap(captureArea.Width, captureArea.Height, g1);
			Graphics g2 = Graphics.FromImage(MyImage);
			Visible = false;
			dc1 = g1.GetHdc();
			IntPtr dc2 = g2.GetHdc();
			WinAPI.BitBlt(dc2, 0, 0, captureArea.Width, captureArea.Height, dc1, Left+captureArea.X, Top + captureArea.Y, 13369376);
			g1.ReleaseHdc(dc1);
			g2.ReleaseHdc(dc2);
			Visible = true;
			g2.Dispose();
			return MyImage;
		}

		private void WeysForm_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			if(e.Button == MouseButtons.Right)
				contextMenu.Show(this, new Point(e.X, e.Y));
		}

		private void WeysForm_DoubleClick(object sender, System.EventArgs e)
		{
			menuItemCaptureSave_Click(null, null);
		}

		public static void ConvertSkinFormat()
		{
			string [] files = Directory.GetFiles(@".\skins", "*.inf");
			foreach(string f in files)
			{
				Skin skin = new Skin();
				
				skin.Name = f.Substring(8,f.Length -12);
				skin.Mode = 0;
				skin.ModeCount = 1;
				skin.IsImageShared = false;
				skin.Pieces = new SkinPiece[2];
				skin.Pieces[0] = new SkinPiece();
				skin.ActiveSkin.Name = "";
				
				StreamReader sr = new StreamReader(f);
				
				string s = sr.ReadLine();
				if(s.Trim() == "") s = sr.ReadLine();
				s = s.Substring(8);
				skin.ActiveSkin.SkinImage = new Bitmap(@".\skins\"+s);
				s.Trim();
				
				s = sr.ReadLine();
				if(s.Trim() == "") s = sr.ReadLine();
				s = s.Substring(s.IndexOf("(")+1);
				string x,y,w,h;
				s = s.Trim();
				s = s.Substring(0, s.Length - 1);
				x = s.Substring(0, s.IndexOf(",") );
				s = s.Substring(s.IndexOf(",")+1);
				y = s.Substring(0, s.IndexOf(",") );
				s = s.Substring(s.IndexOf(",")+1);
				w = s.Substring(0, s.IndexOf(",") );
				h = s.Substring(s.IndexOf(",")+1);

				skin.ActiveSkin.CaptureAreaOffset  = new Point (int.Parse(x.Trim()), int.Parse(y.Trim()));
				skin.ActiveSkin.CaptureAreaSize = new Size (int.Parse(w.Trim()), int.Parse(h.Trim()));
				
				skin.Brand = "Undefined";
				skin.IsTransparencyEnabled = true;
				skin.IsImageShared = false;
				skin.ModelName = skin.Name;
				skin.TransparencyColor = Color.FromArgb(200,255,200);
				
				
				skin.TransparencyColor = ((Bitmap)skin.ActiveSkin.SkinImage).GetPixel(0,0);
				skin.IsTransparencyEnabled = true;

				skin.Save(f.Substring(0, f.Length - 4) + ".xml");
				
			}
		}
		
		private void SkinMenuItem_Click(object sender, System.EventArgs e)
		{
			foreach(MenuItem mi in menuItemSkins.MenuItems)
				mi.Checked = false;
			((MenuItem)sender).Checked = true;
			ApplySkin( Skin.Load((String)((MenuItem)sender).Tag));
		}
		private void ApplySkin(Skin s)
		{
			if(skin != s && s == null)
			{
				Left = Left + captureArea.X - BANNER.X;
				Top = Top + captureArea.Y - BANNER.Y;
			}
			skin = s;
			if(s == null)
			{
				textBoxWidth.Visible = true;
				textBoxHeight.Visible = true;
				pictureBox1.Visible = true;
				
				captureArea.X = BANNER.X;
				captureArea.Y = BANNER.Y;
				Width = captureArea.Width + BANNER.Width;
				Height = captureArea.Height + BANNER.Height;
				SetTransparency();
				Refresh();
			}
			else
			{
				textBoxWidth.Visible = false;
				textBoxHeight.Visible = false;
				pictureBox1.Visible = false;
				
				Hide();
				Rectangle newArea = new Rectangle( skin.ActiveSkin.CaptureAreaOffset, skin.ActiveSkin.CaptureAreaSize);
				Left = Left + captureArea.X - newArea.X + (captureArea.Width - newArea.Width)/2;
				Top = Top + captureArea.Y - newArea.Y + (captureArea.Height - newArea.Height)/2;
				captureArea = newArea;
				Size = skin.ActiveSkin.SkinSize;
				SetTransparency((Bitmap)skin.ActiveSkin.SkinImage, skin.TransparencyColor, skin.ActiveSkin.CaptureAreaOffset, skin.ActiveSkin.CaptureAreaSize);
				Show();
			}
		}

		private void menuItemDefault_Click(object sender, System.EventArgs e)
		{
			foreach(MenuItem mi in menuItemSkins.MenuItems)
				mi.Checked = false;
			((MenuItem)sender).Checked = true;
			//Width = this.captureArea.Width + BANNER.Width;
			//Height = this.captureArea.Height + BANNER.Height;
			ApplySkin(null);
		}

		private void contextMenu_Popup(object sender, System.EventArgs e)
		{
			menuItemSwitch.Enabled = skin != null && skin.ModeCount > 1;
		}

		private void SetTransparency(Bitmap image, Color trans, Point location, Size size)
		{
			IntPtr inner = WinAPI.CreateRectRgn(location.X, location.Y, location.X + size.Width, location.Y + size.Height);
			IntPtr outer = WinAPI.CreateRectRgn(0,0,Width,Height);
			if(skin != null && skin.IsTransparencyEnabled)
			{
				for(int i = 0; i < image.Width; i++)
					for(int j = 0; j < image.Height; j++)
						if(image.GetPixel(i,j) == trans)
						{
							IntPtr rgn = WinAPI.CreateRectRgn(i, j, i+1, j+1);
							WinAPI.CombineRgn(outer, outer, rgn, WinAPI.RGN_DIFF);
							WinAPI.DeleteObject(rgn);
						}
			}
			WinAPI.CombineRgn(outer, outer, inner, WinAPI.RGN_DIFF);
			//this.Hide();
			WinAPI.SetWindowRgn(Handle, outer, true);
			//this.Show();
			//this.WindowState = FormWindowState.Normal;
			WinAPI.DeleteObject(inner);
			WinAPI.DeleteObject(outer);
		}
		private void SetTransparency()
		{
			IntPtr inner = WinAPI.CreateRectRgn(captureArea.Left, captureArea.Top, captureArea.Right, captureArea.Bottom);
			IntPtr outer = WinAPI.CreateRectRgn(0,0,Width,Height);
			WinAPI.CombineRgn(outer, outer, inner, 4);
			//this.Hide();
			WinAPI.SetWindowRgn(Handle, outer, true);
			
			//this.Show();
			//this.WindowState = FormWindowState.Normal;
			WinAPI.DeleteObject(inner);
			WinAPI.DeleteObject(outer);
		}

		private void ApplySize()
		{
			try
			{
				int w = int.Parse(textBoxWidth.Text);
				int h = int.Parse(textBoxHeight.Text);
				captureArea.Width = w;
				captureArea.Height = h;
				Width = w + BANNER.Width;
				Height = h + BANNER.Height;
				SetTransparency();
			}
			catch
			{
				MessageBox.Show(this, "Width and Height have to be integers", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
				
			}
		}

		private void menuItemExit_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}

		private void WeysForm_SizeChanged(object sender, System.EventArgs e)
		{
			textBoxWidth.Text = captureArea.Width.ToString();
			textBoxHeight.Text = captureArea.Height.ToString();
		}
		
		Point mouseOffset;

		private void WeysForm_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			if(e.Button == MouseButtons.Left)
				mouseOffset = new Point(-e.X, -e.Y);
			else if(e.Button == MouseButtons.Middle)
				menuItemCapture_Click(null, null);
		}

		private void WeysForm_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			if (e.Button == MouseButtons.Left) 
			{
				Point mousePos = Control.MousePosition;
				mousePos.Offset(mouseOffset.X, mouseOffset.Y);
				Location = mousePos;
			}
		}
		protected override void OnPaint(PaintEventArgs e)
		{
			if(skin != null)
				
				e.Graphics.DrawImage(skin.ActiveSkin.SkinImage,0,0);
			base.OnPaint (e);
		}

		private void menuItemSwitch_Click(object sender, System.EventArgs e)
		{
			if(skin != null)
				skin.Mode = (skin.Mode + 1) % skin.ModeCount;
			ApplySkin(skin);
			WeysForm_SizeChanged(null, null);
		}

		private void menuItemCapture_Click(object sender, System.EventArgs e)
		{
			Image img = CapturePartial();
			string filename = string.Format(
				"{0,0:D4}{1,0:D02}{2,0:D02}{3,0:D02}{4,0:D02}{5,0:D02}", 
				DateTime.Now.Year,
				DateTime.Now.Month,
				DateTime.Now.Day,
				DateTime.Now.Hour,
				DateTime.Now.Minute,
				DateTime.Now.Second);
			
			if(File.Exists(filename + "." + settings.DefaultSaveFormat))
			{
				int i;
				for(i = 2; File.Exists(filename + "_" + i + "." + settings.DefaultSaveFormat); i++);
				filename = filename + "_" + i;
			}

			if(!Directory.Exists(settings.DefaultSavePath))
				Directory.CreateDirectory(settings.DefaultSavePath);

			img.Save(
				settings.DefaultSavePath + filename + 
				"." + settings.DefaultSaveFormat,
				GetImageFormatFromExt(settings.DefaultSaveFormat)
			);
		}

		private void WeysForm_Load(object sender, System.EventArgs e)
		{
			this.Location = settings.Position;
		}
		private void CenterWindow()
		{
			Left = (Screen.PrimaryScreen.Bounds.Width - Width ) / 2;
			Top =  (Screen.PrimaryScreen.Bounds.Height - Height) / 2;
		}

		private void menuItemCaptureSave_Click(object sender, System.EventArgs e)
		{
			Image img = CapturePartial();
			FileDialog fd = new SaveFileDialog();
			fd.Filter = "*.PNG (Portable Network Graphics)|*.png"+
						"|*.JPG, *.JPEG (JPEG files)"+
						"|*.jpg;*.jpeg|*.BMP (Bitmap)|*.bmp"+
						"|*.GIF (Graphics Interchange Format)|*.gif";

			DialogResult dr = fd.ShowDialog(this);
			if(dr == DialogResult.OK)
			{
				string f = fd.FileName;
				string ext = f.Substring(f.LastIndexOf("."), f.Length - f.LastIndexOf("."));
				img.Save(fd.FileName, GetImageFormatFromExt(ext));
			}
		}
		private ImageFormat GetImageFormatFromExt(string ext)
		{
			ImageFormat format;
			if(ext[0] == '.') ext = ext.Substring(1);
			if(ext.ToLower().Equals("png"))
				format = ImageFormat.Png;
			else if(ext.ToLower().Equals("jpeg") || ext.ToLower().Equals("jpg"))
				format = ImageFormat.Jpeg;
			else if(ext.ToLower().Equals("bmp"))
				format = ImageFormat.Bmp;
			else if(ext.ToLower().Equals("gif"))
				format = ImageFormat.Gif;
			else
				throw new Exception("Extention not recoganized: " + ext);
			return format;
		}

		private void buttonUpdate_Click(object sender, System.EventArgs e)
		{
			UpdateSkinFormat();
		}
		public static void UpdateSkinFormat()
		{
			string [] files = Directory.GetFiles(@".\skins", "*.xml");
			foreach(string f in files)
			{
				Skin s = Skin.Load(f);
				//s.IsTransparencyEnabled = true;
				if(s.Name.ToUpper()[0] == 'N')
				{
					s.Brand = "Nokia";
					s.ModelName = s.Name.Substring(1);
				}
				else
				{
					int index = s.Name.IndexOf("_");
					s.Brand = s.Name.Substring(0,index);
					s.ModelName = s.Name.Substring(index+1);
					if(s.Brand == "SE")
						s.Brand = "Sony Ericsson";
					else if(s.Brand == "MOTO")
						s.Brand = "Motorola";
				}
				s.Save(f);
			}
		}

		private void menuItemSettings_Click(object sender, System.EventArgs e)
		{
			System.Diagnostics.Process proc = new System.Diagnostics.Process();
			proc.EnableRaisingEvents=false;
			proc.StartInfo.FileName="notepad";
			proc.StartInfo.Arguments="settings.xml";
			proc.Start();
			proc.WaitForExit(); //block the calling process
			LoadSettings(); //reload the settings upon finishing editing
		}

		public static void ExportAsWebPage()
		{
			Directory.CreateDirectory(@".\webpage\res");
			Directory.CreateDirectory(@".\webpage\skins");
			string [] files = Directory.GetFiles(@".\skins", "*.xml");
			StreamWriter sw = new StreamWriter(File.Create(@".\webpage\index.htm"));

			//write header
			StreamReader sr = new StreamReader("./res/index1.htm");
			sw.Write(sr.ReadToEnd());
			sr.Close();

			foreach(string f in files)
			{
				File.Copy(f, @".\webpage\" + f, true);
				Skin s = Skin.Load(f);
				string skinfile =  s.Brand + "_" + s.ModelName + ".htm";
				ExportSkinPage(s, @".\webpage\" + skinfile);
				sw.Write("<P><FONT face=\"Arial\">" + s.Brand + "&nbsp;" + s.ModelName + "&nbsp;&nbsp;<A href=\""+ f 
						+"\">Download</A>&nbsp;&nbsp;<A href=\""+ skinfile +"\">Preview</A></FONT></P>");
			}

			//write file tail
			sr = new StreamReader("./res/index2.htm");
			sw.Write(sr.ReadToEnd());
			sr.Close();
			sw.Close();
		}
		public static void ExportSkinPage(Skin s, string path)
		{
			StreamWriter sw = new StreamWriter(File.Create(path));
			//write header
			StreamReader sr = new StreamReader("./res/skin1.htm");
			sw.Write(sr.ReadToEnd());
			sr.Close();

			sw.Write("<p align=\"center\">");
			foreach(SkinPiece sp in s.Pieces)
			//SkinPiece sp = s.Pieces[0];
			{

				if(sp.SkinImage == null)
					sp.SkinImage = s.Pieces[0].SkinImage;

				Bitmap bmp = new Bitmap(sp.SkinImage.Width, sp.SkinImage.Height, PixelFormat.Format32bppArgb);
				/*for(int i = 0; i < bmp.Width; i++)
					for(int j = 0; j < bmp.Height; j++)
					{
						if(i >= sp.CaptureAreaOffset.X && i < sp.CaptureAreaOffset.X + sp.CaptureAreaSize.Width
							&& j > sp.CaptureAreaOffset.Y && j < sp.CaptureAreaOffset.Y + sp.CaptureAreaSize.Height)
							bmp.SetPixel(i,j,s.TransparencyColor);
						else
							bmp.SetPixel(i,j,sp.SkinImage.GetPixel(i,j));
					}
				*/
				
				Graphics g = Graphics.FromImage(bmp);
				g.DrawImage(sp.SkinImage, 0, 0);
				Color color = Color.FromArgb(255, s.TransparencyColor);
				g.FillRectangle(new SolidBrush(color),new Rectangle(sp.CaptureAreaOffset, sp.CaptureAreaSize));
				g.Dispose();

				if(s.IsTransparencyEnabled)
					bmp.MakeTransparent(s.TransparencyColor);
				string imgfile = s.Name + "_" + sp.Name + ".png";
				bmp.Save(@".\webpage\res\" + imgfile, ImageFormat.Png);
				sw.Write("<img width=" + bmp.Width + " height=" + bmp.Height + " src=\"" + @"./res/" + imgfile + "\"></img>");
			}
			sw.Write("</p>");
			sr = new StreamReader("./res/skin2.htm");
			sw.Write(sr.ReadToEnd());
			sr.Close();
			sw.Close();
		}

		private void WeysForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			if(skin == null)
			{
				settings.SkinFileName = "";
				settings.DefaultCaptureSize = captureArea.Size;
			}
			else
			{
				settings.SkinFileName = skin.Name + ".xml";
				settings.SkinMode = skin.Mode;
			}
			settings.Position = this.Location;
			settings.Save(settings.SettingFilePath + "\\" + "settings.xml");
		}

		private void menuItemHelp_Click(object sender, System.EventArgs e)
		{
			System.Diagnostics.Process proc = new System.Diagnostics.Process();
			proc.EnableRaisingEvents=false;
			proc.StartInfo.FileName="readme.htm";
			proc.Start();
		}

		private void menuItemAbout_Click(object sender, System.EventArgs e)
		{
            if (aboutDialog == null)
            {
                string msg = string.Format("Weys Version {0}\r\nCopyright (C) Lu Yixiang 2005 - 2007", Application.ProductVersion);
                MessageBox.Show(this, msg, "About Weys", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                aboutDialog.TopMost = true;
                aboutDialog.ShowDialog();
            }
		}

		private void WeysForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			int increment;
			if((e.Modifiers & Keys.Control) == Keys.Control)
				increment = 100;
			else if((e.Modifiers & Keys.Shift) == Keys.Shift)
				increment = 10;
			else
				increment = 1;

			bool resize = false;;
			if((e.Modifiers & Keys.Alt) == Keys.Alt && skin == null)
				resize = true;

			if(e.KeyCode == Keys.PageUp)
			{
				int i;
				for(i = 0; i < menuItemSkins.MenuItems.Count && !menuItemSkins.MenuItems[i].Checked; i++);

				menuItemSkins.MenuItems[i].Checked = false;
				if(--i < 2)
					i = menuItemSkins.MenuItems.Count - 1;
				if(menuItemSkins.MenuItems[i].Text == "-")
					i--;
				menuItemSkins.MenuItems[i].Checked = true;

				if(menuItemSkins.MenuItems[i].Text == "Plain (Sizable)")
					ApplySkin(null);
				else
					SkinMenuItem_Click(menuItemSkins.MenuItems[i], null);
			}
			else if(e.KeyCode == Keys.PageDown)
			{
				int i;
				for(i = 0; i < menuItemSkins.MenuItems.Count && !menuItemSkins.MenuItems[i].Checked; i++);	
				
				menuItemSkins.MenuItems[i].Checked = false;
				if(++i > menuItemSkins.MenuItems.Count - 1)
					i = 2;
				if(menuItemSkins.MenuItems[i].Text == "-")
					i++;
				menuItemSkins.MenuItems[i].Checked = true;
				
				if(menuItemSkins.MenuItems[i].Text == "Plain (Sizable)")
					ApplySkin(null);
				else
					SkinMenuItem_Click(menuItemSkins.MenuItems[i], null);
			}
			else if(e.KeyCode == Keys.Home)
			{
				foreach(MenuItem mi in menuItemSkins.MenuItems)
					if(mi.Text == "Plain (Sizable)")
						mi.Checked = true;
					else
						mi.Checked = false;
				ApplySkin(null);
			}
			else if(e.KeyCode == Keys.Up)
			{
				if(resize)
				{
					captureArea.Height -= increment;
					Height -= increment;
					ApplySkin(null);
				}
				else
					this.Top -= increment;
			}
			else if(e.KeyCode == Keys.Down)
			{
				if(resize)
				{
					captureArea.Height += increment;
					Height += increment;
					ApplySkin(null);
				}
				else
					this.Top += increment;
			}
			else if(e.KeyCode == Keys.Left)
			{
				if(resize)
				{
					captureArea.Width -= increment;
					Width -= increment;
					ApplySkin(null);
				}
				else
					this.Left -= increment;
			}
			else if(e.KeyCode == Keys.Right)
			{
				if(resize)
				{
					captureArea.Width += increment;
					Width += increment;
					ApplySkin(null);
				}
				else
					this.Left += increment;
			}
		}

		private void textBoxWidth_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			if(e.KeyCode == Keys.Enter)
				ApplySize();
			else
				WeysForm_KeyDown(sender, e);
		}
		private void textBoxHeight_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			if(e.KeyCode == Keys.Enter)
				ApplySize();
			else
				WeysForm_KeyDown(sender, e);
		}

		Point mouseDownPoint = new Point(0,0);
		private void pictureBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			mouseDownPoint.X = e.X;
			mouseDownPoint.Y = e.Y;
		}

		private void pictureBox1_MouseEnter(object sender, System.EventArgs e)
		{
			this.Cursor = Cursors.SizeNWSE;
		}

		private void pictureBox1_MouseLeave(object sender, System.EventArgs e)
		{
			this.Cursor = Cursors.Arrow;
		}

		private void pictureBox1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			if(e.Button == MouseButtons.Left)
			{
				Size ds = new Size(e.X - mouseDownPoint.X, e.Y - mouseDownPoint.Y);
				Size = new Size(Width + ds.Width, Height + ds.Height);

				//captureArea.Width -= ds.Width;
				//captureArea.Height -= ds.Height;
				
				//if(captureArea.Width < 1)
				//	captureArea.Width = 1;
				//if(captureArea.Height < 1)
				//	captureArea.Height = 1;

				//SetTransparency();
				captureArea.Width = Width - BANNER.Width;
				captureArea.Height = Height - BANNER.Height;

				ApplySkin(null);
			}
		}
	}
}
